# nacos/client.py

import logging
import time
import threading
import requests
from nacos.token_manager import get_current_token, refresh_token_if_needed

# 配置日志
logging.basicConfig(level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s")
logger = logging.getLogger(__name__)

# 配置常量
NACOS_SERVER = "http://129.211.24.193:8848/nacos"  # Nacos 服务器地址
NACOS_NAMESPACE = "fb188d1e-e0eb-4e22-94db-769c583c8a88"  # Nacos 命名空间
GROUP_NAME = "lw"  # 服务组名
SERVICE_NAME = "flask-service"  # 服务名称
SERVICE_IP = "127.0.0.1"  # 服务 IP
SERVICE_PORT = 5000  # 服务端口
REGISTER_URL = f"{NACOS_SERVER}/v2/ns/instance"  # 服务注册接口
HEARTBEAT_URL = f"{NACOS_SERVER}/v2/ns/instance/beat"  # 心跳接口

service_name_with_group = f"{GROUP_NAME}@@{SERVICE_NAME}"
def register_service_to_nacos():
    """
    将服务注册到 Nacos。
    """
    refresh_token_if_needed()  # 注册前检查并刷新 Token

    # 注册服务的 payload
    payload = {
        "namespaceId": NACOS_NAMESPACE,
        "serviceName": SERVICE_NAME,
        "groupName": GROUP_NAME,
        "ip": SERVICE_IP,
        "port": SERVICE_PORT,
        "weight": 1.0,
        "clusterName": "DEFAULT"
    }

    # 获取当前 Token
    current_token = get_current_token()

    # Token 不存在时，等待并重新获取
    if current_token is None:
        logger.error("No token available. Retrying...")
        return

    headers = {
        "Authorization": f"Bearer {current_token}",
        "Content-Type": "application/x-www-form-urlencoded"
    }

    try:
        response = requests.post(REGISTER_URL, data=payload, headers=headers)
        if response.status_code == 200:
            logger.info(f"Service {SERVICE_NAME} registered successfully.")
        else:
            logger.error(f"Failed to register service: {response.text}")
    except requests.exceptions.RequestException as e:
        logger.error(f"Error registering service: {e}")


def send_heartbeat():
    """
    定期向 Nacos 发送心跳，保持服务活跃。
    """
    while True:
        refresh_token_if_needed()  # 每次发送心跳前检查 Token 是否有效

        # 获取当前 Token
        current_token = get_current_token()

        # Token 不存在时，等待并重新获取
        if current_token is None:
            logger.error("No token available. Retrying...")
            time.sleep(5)
            continue

        # 心跳 payload
        heartbeat_payload = {
            "serviceName": service_name_with_group,
            "ip": SERVICE_IP,
            "port": SERVICE_PORT,
            "namespaceId": NACOS_NAMESPACE,
        }

        headers = {
            "Authorization": f"Bearer {current_token}",
            "Content-Type": "application/x-www-form-urlencoded"
        }

        try:
            response = requests.put(HEARTBEAT_URL, data=heartbeat_payload, headers=headers)
            if response.status_code == 200:
                logger.info("Heartbeat sent successfully.")
            else:
                logger.warning(f"Failed to send heartbeat: {response.text}")
        except requests.exceptions.RequestException as e:
            logger.error(f"Error sending heartbeat: {e}")

        time.sleep(20)  # 每 20 秒发送一次心跳


def start_nacos_service():
    """
    启动 Nacos 服务注册和心跳发送功能。
    """
    # 注册服务
    register_service_to_nacos()

    # 启动心跳线程
    def heartbeat_thread():
        send_heartbeat()

    threading.Thread(target=heartbeat_thread, daemon=True).start()
